<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue'
import { registerMap } from 'echarts'
import worldCh from '@/assets/json/worldCh.json'
import { HttpCodeEnum } from '@packages/share/enums'
import { useWorldMap } from '@/hooks/chart/useWorldMap'
// 引入接口
import { getMapAPI } from '@/api/vulnerability/fore'

const emit = defineEmits(['update'])
const { options } = useWorldMap()
const chartRef = ref()
const ForeValue = reactive({
  cve: ''
})
// 绑定接收：时间
const props = defineProps({
  time: {
    type: Object,
    required: true,
    default: () => {}
  }
})
// 接收CVE码
const show = (value: string) => {
  ForeValue.cve = value
  value && getInfo(true)
}
// 图例最大值
const legendMax=(data:Array<any>)=>{
  const valueArray = data.map(obj => obj.value);
  // 找到value数组中的最大值作为图例上限(10为计量单位)
  const maxValue = Math.ceil(Math.max(...valueArray)/10)*10;
  return maxValue
}
// 地图初始化
const mapInit = () => {
  //@ts-ignore
  registerMap('world', worldCh)
  chartRef.value.loadingChart(true)
  chartRef.value.initChart()
  chartRef.value.clickChart(mapClick)
  getInfo(false)
}
// 地图数据请求
const getInfo = (flag: boolean) => {
  getMapAPI({ ...props.time, ...ForeValue }).then((res) => {
    let { data, code } = res.data
    if (code === HttpCodeEnum.SUCCESS) {
      options.series[0].data = data
      options.visualMap.max = legendMax(data) //将数据最大值作为图例上限
      flag ? chartRef.value.updateChart() : chartRef.value.initChart()
    }
  })
}
// 地图点击抛出地名
const mapClick = (e: any) => {
  emit('update', e.name)
}
onMounted(() => {
  mapInit()
})
defineExpose({ show })
</script>

<template>
  <div class="chart-content">
    <jmp-chart ref="chartRef" v-model:option="options"></jmp-chart>
  </div>
</template>
